import {
  doLoginApi
} from '@/api/userApi'
import Store from '@/utils/store'
import {
  hasToken
} from '@/utils/token'
const sessionStore = new Store()

export default {
  state: {
    roleid: 0,
    token: '',
    nickname: '',
    routes: []
  },
  mutations: {
    // 写入vuex的同时，进行本地存储,为了持久化
    setUserLoginInfo(state, payload) {
      state.token = payload.token
      state.nickname = payload.nickname;
      state.routes = payload.routes;
      state.roleid = payload.roleid;
      !hasToken() && setStorage(payload)
    },
    userLogout(state, payload) {
      state.token = ''
      state.nickname = ''
      state.routes = []
      state.roleid = 0
      sessionStore.remove('token')
      sessionStore.remove('nickname')
      sessionStore.remove('routes')
      sessionStore.remove('roleid')
      window.location.href = '/login'
    }
  },
  actions: {
    // 进行网络请求的调用，验证账号和密码是否正确
    async fetchUserLogin({
      commit
    }, payload) {
      let ret = await doLoginApi(payload)
      // 通知vuex中的state来修改对应的token数据
      commit('setUserLoginInfo', ret.data)
      return ret.code
    }
  }
}


function setStorage({
  token,
  nickname,
  routes,
  roleid
}) {
  sessionStore.set('token', token)
  sessionStore.set('nickname', nickname)
  sessionStore.set('routes', routes)
  sessionStore.set('roleid', roleid)
}